/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EmployeeEditPanel.java
 *
 * Created on Apr 15, 2010, 5:43:57 PM
 */

package edu.asu.cse360.client.ui.frame;

import edu.asu.cse360.client.context.RestaurantContext;
import edu.asu.cse360.client.util.PasswordUtils;
import edu.asu.cse360.context.ServiceFactory;
import edu.asu.cse360.model.Chef;
import edu.asu.cse360.model.Credentials;
import edu.asu.cse360.model.Employee;
import edu.asu.cse360.model.Manager;
import edu.asu.cse360.model.WaitPerson;
import edu.asu.cse360.service.EmployeeService;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;

/**
 *This class is responsible to edit the employees in the system, but only the manager can edit the employees
 * @author ggreiner
 */
public class EmployeeEditPanel extends javax.swing.JPanel {

    private static EmployeeEditPanel instance;
    public static EmployeeEditPanel instance() {
        if(instance == null){
            instance = new EmployeeEditPanel();
        }
        return instance;
    }

    private EmployeeTableModel tableModel;
    private EmployeeService employeeSvc;
    private Employee selectedEmployee;
    private boolean flag = false;
    /** Creates new form EmployeeEditPanel */
    private EmployeeEditPanel() {
        employeeSvc = ServiceFactory.getEmployeeService();
        tableModel = new EmployeeTableModel();
        initComponents();
        refreshTableModel();
        employeeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                if(!e.getValueIsAdjusting()){
                    handleListSelection();
                }
            }
        });
        if(tableModel.getRowCount() > 0){
            employeeTable.setRowSelectionInterval(0,0);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        employeeTable = new javax.swing.JTable();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        infoTabbedPane = new javax.swing.JTabbedPane();
        generalPanel = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        usernameTxt = new javax.swing.JTextField();
        firstNameTxt = new javax.swing.JTextField();
        lastNameTxt = new javax.swing.JTextField();
        positionTxt = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        newPasswordTxt = new javax.swing.JPasswordField();
        repeatPasswordTxt = new javax.swing.JPasswordField();
        jLabel7 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        employeeTable.setModel(getTableModel());
        employeeTable.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
                employeeTableCaretPositionChanged(evt);
            }
        });
        employeeTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                employeeTablePropertyChange(evt);
            }
        });
        jScrollPane1.setViewportView(employeeTable);

        jButton4.setText("New Employee");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Delete Employee");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setText("Refresh");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(26, 26, 26)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jButton6)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jButton4)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton5))
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 306, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(220, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(25, 25, 25)
                .add(jButton6)
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton4)
                    .add(jButton5))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 257, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(141, Short.MAX_VALUE))
        );

        jLabel1.setText("Username:");

        jLabel2.setText("First Name:");

        jLabel3.setText("Last Name:");

        jLabel4.setText("Position:");

        positionTxt.setEnabled(false);

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                .add(65, 65, 65)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                        .add(6, 6, 6)
                        .add(jLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(usernameTxt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                        .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jLabel2)
                            .add(jLabel3)
                            .add(jLabel4))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(firstNameTxt)
                            .add(lastNameTxt)
                            .add(positionTxt, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 160, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                .add(31, 31, 31))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(20, Short.MAX_VALUE)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(usernameTxt, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(firstNameTxt, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel2))
                .add(18, 18, 18)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lastNameTxt, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel3))
                .add(20, 20, 20)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(positionTxt, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jButton3.setText("Revert Changes");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton2.setText("Save Changes");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout generalPanelLayout = new org.jdesktop.layout.GroupLayout(generalPanel);
        generalPanel.setLayout(generalPanelLayout);
        generalPanelLayout.setHorizontalGroup(
            generalPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(generalPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(33, Short.MAX_VALUE))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, generalPanelLayout.createSequentialGroup()
                .addContainerGap(51, Short.MAX_VALUE)
                .add(jButton2)
                .add(18, 18, 18)
                .add(jButton3)
                .add(51, 51, 51))
        );
        generalPanelLayout.setVerticalGroup(
            generalPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(generalPanelLayout.createSequentialGroup()
                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(generalPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton2)
                    .add(jButton3))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        infoTabbedPane.addTab("General Information", generalPanel);

        jLabel6.setText("New Password:");

        jLabel7.setText("Repeat Password:");

        jButton1.setText("Change Password");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel5Layout.createSequentialGroup()
                .add(46, 46, 46)
                .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel5Layout.createSequentialGroup()
                        .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jLabel7)
                            .add(jLabel6))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(newPasswordTxt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE)
                            .add(repeatPasswordTxt, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 154, Short.MAX_VALUE)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel5Layout.createSequentialGroup()
                        .add(119, 119, 119)
                        .add(jButton1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .add(72, 72, 72))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel5Layout.createSequentialGroup()
                .add(66, 66, 66)
                .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel6)
                    .add(newPasswordTxt, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel7)
                    .add(repeatPasswordTxt, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(18, 18, 18)
                .add(jButton1)
                .addContainerGap(85, Short.MAX_VALUE))
        );

        infoTabbedPane.addTab("Password", jPanel5);

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(infoTabbedPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(infoTabbedPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 308, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(200, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 236, Short.MAX_VALUE)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        handleChangePassword();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        handleSave();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        handleRevertChanges();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        handleNewEmployee();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        handleDeleteEmployee();
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        this.refreshTableModel();
    }//GEN-LAST:event_jButton6ActionPerformed

    private void employeeTablePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_employeeTablePropertyChange

    }//GEN-LAST:event_employeeTablePropertyChange

    private void employeeTableCaretPositionChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_employeeTableCaretPositionChanged

    }//GEN-LAST:event_employeeTableCaretPositionChanged



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable employeeTable;
    private javax.swing.JTextField firstNameTxt;
    private javax.swing.JPanel generalPanel;
    private javax.swing.JTabbedPane infoTabbedPane;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField lastNameTxt;
    private javax.swing.JPasswordField newPasswordTxt;
    private javax.swing.JTextField positionTxt;
    private javax.swing.JPasswordField repeatPasswordTxt;
    private javax.swing.JTextField usernameTxt;
    // End of variables declaration//GEN-END:variables

    public JTable getEmployeeTable(){
        return employeeTable;
    }
    private EmployeeTableModel getTableModel(){
        return tableModel;
    }

    private boolean validatePasswords() {
        String pwd1 = getPasswordText(newPasswordTxt.getPassword());
        String pwd2 = getPasswordText(repeatPasswordTxt.getPassword());
        boolean valid = false;
        if(pwd1.isEmpty() || pwd2.isEmpty()){
            JOptionPane.showMessageDialog(this, "Passwords must not be empty");
            valid = false;
        }else if(pwd1.equals(pwd2)){
          valid = true;
        }else{
            valid = false;
            JOptionPane.showMessageDialog(this, "Passwords do not match.");
        }
        return valid;
    }

//    tableModel.addTableModelListener(new java.awt.event.TableModelListener());


    public class TableModelListener implements ListSelectionListener{

        public void valueChanged(ListSelectionEvent e) {

            if(flag)
                tableModel.removeEmployee(selectedEmployee);
        }

       

    }
    public void refreshTableModel() {
        List<Employee> employees = employeeSvc.getEmployees(RestaurantContext.getRestaurant());
        tableModel.setEmployees(employees);
    }

    private void updateFormFields() {
        clearPasswordFields();
        if(selectedEmployee == null){
            clearEmployeeFields();
        }else{
            usernameTxt.setText(selectedEmployee.getCredentials().getUsername());
            firstNameTxt.setText(selectedEmployee.getFirstName());
            lastNameTxt.setText(selectedEmployee.getLastName());
            positionTxt.setText(selectedEmployee.getClass().getSimpleName());
        }
    }

    private void clearEmployeeFields() {
        clearField(usernameTxt);
        clearField(firstNameTxt);
        clearField(lastNameTxt);
        clearField(positionTxt);
    }


    private void handleListSelection() {
        int selectedRow = employeeTable.getSelectedRow();
        if(selectedRow == -1){
            selectedEmployee = null;
        }else{
            selectedEmployee = tableModel.getEmployeeAt(selectedRow);
        }
        updateFormFields();
    }

    private void handleSave() {
        updateEmployeeFromFields();
        if(selectedEmployee != null){
            int seletedRow = tableModel.getSelectedRow(selectedEmployee);
            if(selectedEmployee.getId() == null){
                if(!validatePasswords()){
                    return;
                }else{
                    String pwd1 = getPasswordText(newPasswordTxt.getPassword());
                    selectedEmployee.getCredentials().setPassword(pwd1);
                }
            }
            //tableModel.fireTableRowsUpdated(seletedRow, seletedRow);
            if(validateBeforeSave()){
                selectedEmployee = employeeSvc.save(selectedEmployee);
                int employeeIndex = tableModel.indexOf(selectedEmployee);
                tableModel.updateEmployee(selectedEmployee.getId(), selectedEmployee);               
                employeeTable.setRowSelectionInterval(employeeIndex,employeeIndex);
            }
            else{
                JOptionPane.showMessageDialog(null, "Cannot save this employee, Username and Password are Required");
            }
        }
    }

    private void updateEmployeeFromFields() {
        if(selectedEmployee != null){
            selectedEmployee.setFirstName(firstNameTxt.getText());
            selectedEmployee.setLastName(lastNameTxt.getText());
            selectedEmployee.getCredentials().setUsername(usernameTxt.getText());
        }
    }

    private void handleRevertChanges() {
        updateFormFields();
    }

    private void handleChangePassword() { 
        String pwd1 = getPasswordText(newPasswordTxt.getPassword());
        if(validatePasswords()){
            String md5password = PasswordUtils.getMD5Password(pwd1);
            selectedEmployee.getCredentials().setPassword(md5password);
            selectedEmployee = employeeSvc.save(selectedEmployee);
            int employeeIndex = tableModel.indexOf(selectedEmployee);
            tableModel.updateEmployee(selectedEmployee.getId(), selectedEmployee);
            employeeTable.setRowSelectionInterval(employeeIndex,employeeIndex);
            JOptionPane.showMessageDialog(this, "Password saved successfully.");
        }
        
    }

    private String getPasswordText(char[] chars) {
        return new String(chars);
    }

    private void clearPasswordFields() {
        clearField(newPasswordTxt);
        clearField(repeatPasswordTxt);
    }

    private void clearField(JTextField txt) {
        txt.setText("");
    }

    private void handleNewEmployee() {
        String[] comboValues = new String[]{"Wait Person", "Chef", "Manager"};
        String selectedValue = comboValues[0];
        String userSelection = (String)JOptionPane.showInputDialog(this, "Employee Type", "Select Employee Type", JOptionPane.QUESTION_MESSAGE, null, comboValues, selectedValue);
        Employee employee;
        if(userSelection.equals(comboValues[0])){
            employee = new WaitPerson();
        }else if(userSelection.equals(comboValues[1])){
            employee = new Chef();
        }else{
             employee = new Manager();
         }
        setDefaultFields(employee);
        tableModel.addEmployee(employee);
        flag = true;
        int seletedRow = tableModel.getSelectedRow(employee);
        employeeTable.setRowSelectionInterval(seletedRow,seletedRow);
        infoTabbedPane.setSelectedComponent(generalPanel);
    }

    private void handleDeleteEmployee() {
        if(selectedEmployee == null) return;
        String employeeName = selectedEmployee.getFirstName() + " " +selectedEmployee.getLastName();
        int selection = JOptionPane.showConfirmDialog(this, "Are you sure you wish to delete employee "+employeeName+"?", "Delete Employee", JOptionPane.OK_CANCEL_OPTION);
        if(selection == JOptionPane.OK_OPTION){
            employeeSvc.remove(selectedEmployee);
            tableModel.removeEmployee(selectedEmployee);
        }
    }

    private void setDefaultFields(Employee employee) {
        employee.setCredentials(getDefaultCredentials());
        employee.setFirstName("New");
        employee.setLastName("Employee");
        employee.setRestaurant(RestaurantContext.getRestaurant());
    }

    private Credentials getDefaultCredentials(){
        Credentials defaultCreds = new Credentials();
        defaultCreds.setUsername("");
        defaultCreds.setPassword("");
        return defaultCreds;
    }

    private boolean validateBeforeSave() {
    return (selectedEmployee.getCredentials() != null && !selectedEmployee.getCredentials().getUsername().equals(null) && !selectedEmployee.getCredentials().getPassword().equals(null) && !selectedEmployee.getCredentials().getUsername().isEmpty() && !selectedEmployee.getCredentials().getPassword().isEmpty());
    }

    public void refresh() {
        this.refreshTableModel();
    }


    private class EmployeeTableModel extends AbstractTableModel{
        private List<Employee> employees;
        private String[] columns = new String[]{"Name", "Employee Type"};

        public EmployeeTableModel(){
            this.employees = new ArrayList<Employee>();
        }
        public int getRowCount() {
            return this.employees.size();
        }

        public int getColumnCount() {
            return columns.length;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            Employee employee = employees.get(rowIndex);
            Object value = null;
            switch(columnIndex){
                case 0:
                    value = employee.getFirstName() + " "+employee.getLastName();
                    break;
                case 1:
                    value = employee.getClass().getSimpleName();
                    break;

            }
            return value;
        }

        @Override
        public String getColumnName(int columnIndex){
            return columns[columnIndex];
        }

        public void setEmployees(List<Employee> employees){
            this.employees.clear();
            if(employees != null){
                this.employees.addAll(employees);
            }
            super.fireTableDataChanged();
        }

        private Employee getEmployeeAt(int index) {
            return this.employees.get(index);
        }

        private int getSelectedRow(Employee employee) {
            return this.employees.indexOf(employee);
        }

        private void addEmployee(Employee employee) {
            this.employees.add(employee);
            super.fireTableDataChanged();
        }

        private void removeEmployee(Employee employee) {
            this.employees.remove(employee);
            super.fireTableDataChanged();
        }
        public void updateEmployee(Integer id, Employee employee){
            int index = 0;
            for(Employee oldEmployee:employees){
                if(oldEmployee.getId().equals(id)){
                    employees.set(index, employee);
                    break;
                }
                index++;
            }
            super.fireTableDataChanged();
        }

        private int indexOf(Employee employee) {
            int index = 0;
            for(Employee emp: employees){
                if(emp.getId() != null && emp.getId().equals(employee.getId())){
                    return index;
                }
                index++;
            }
            return -1;
        }
        
    }
}
